package com.dmx.cep.job;

import java.util.Calendar;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dmx.cep.constant.ConfAttributeConstant;
import com.dmx.cep.entity.ConfAttributeSelection;
import com.dmx.cep.service.EpgService;
import com.dmx.fw.util.DateTimeUtils;

public class EpgDeleteJob {
	
	private Log log=LogFactory.getLog(EpgDeleteJob.class);
	
	private EpgService epgService;
	
	private int maxResults=100;
	
	private int sleepTime=2000;
	
	public void execute(){
		
		log.info("delete expired EPG job execute.....");
		
		try {
			ConfAttributeSelection confAttribute=epgService.getConfAttributeByKey(ConfAttributeConstant.KEY_EPG_EXPIRE_DAY);
			
			int expireDays = 7;
			if (confAttribute != null) {
				try {
					int value = confAttribute.getConfValue().intValue();
					if(value>0) expireDays=value;
				} catch (Exception e) {
					expireDays = 7;
				}
			}
			log.info("EPG expired days="+expireDays);
			Calendar validDate=Calendar.getInstance();
			validDate.add(Calendar.DAY_OF_MONTH, -expireDays);
			log.info("valid date="+DateTimeUtils.DateToString(validDate.getTime(), "yyyy-MM-dd HH:mm:ss"));
			
			while (true) {
				Integer deleteCounts = epgService.deleteExpiredEpgData(validDate.getTime(), maxResults);
				
				log.info("delete EPG counts="+deleteCounts.intValue());
				
				if(deleteCounts.intValue()<maxResults) break;
				
				Thread.sleep(sleepTime);
				
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("delete expired EPG job error:",e);
		}
		
		log.info("delete expired EPG job end.");
	}

	public EpgService getEpgService() {
		return epgService;
	}

	public void setEpgService(EpgService epgService) {
		this.epgService = epgService;
	}

	public int getMaxResults() {
		return maxResults;
	}

	public void setMaxResults(int maxResults) {
		this.maxResults = maxResults;
	}

	public int getSleepTime() {
		return sleepTime;
	}

	public void setSleepTime(int sleepTime) {
		this.sleepTime = sleepTime;
	}
	
}
